"""
    Controller only for spent lesson viewing, not for editing.
"""

from turbogears.widgets import TextField
from mnemoply import utils
from mnemoply import model
from mnemoply.widgets import DecimalValidator
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import CRUDController
from mnemoply.mass_actions import MassAction, MassActionForm

class MAClearTeacher(MassAction):
    target_class = model.SpentLesson
    name = "clear_teacher"
    title = _("Clear teacher")
    def call(self, objs):
        beginning_date, ending_date = utils.getHalfMonthBeforeToday()
        for lesson in objs:
            if beginning_date < lesson.date < ending_date:
                lesson.destroySelf()

class MAChangeHours(MassAction):
    target_class = model.SpentLesson
    name = "change_hours"
    title = _("Change hours")
    form = MassActionForm(name=name,
        fields=[
            TextField(name = "hours",
                      label=_("Spent hours"),
                      validator=DecimalValidator(not_empty=False)),
        ]
    )

    def call(self, objs, hours):
        for sl in objs:
            if sl.lessonAssistantType.stringId == 'defence_assistant':
                sl.lessonPeriod = hours

class SpentLessonController(LookupController, CRUDController):
    model_object = model.SpentLesson
    lookup_columns = [
        TableCol(name='group_title', caption=_("Group")),
        TableCol(name='date', caption=_("Date")),
        TableCol(name='group_teacher', caption=_("Current group teacher")),
        TableCol(name='spent_lesson_teacher', caption=_("Spent lesson teacher")),
        TableCol(name='num_students', caption=_("Number of students")),
        TableCol(name='lesson_period', caption=_("Lesson period")),
        TableCol(name='lesson_assistant_type', caption=_("Lesson assistant type"), hidden=True),
        TableCol(name='teacher_tariff', caption=_("Teacher tariff"), hidden=True),
    ]
    view_fields = ['date', 'groupID']
    edit_fields = []

    def __init__(self):
        LookupController.__init__(self,
            data_source=TableLookupDataSource("spent_lesson_lookup"),
            columns=self.lookup_columns,
            mass_actions_class=self.model_object,
            title=self.model_object.model_title,
            default_order_by='date',
            default_order_asc=False,
            default_filters={},
        )
        CRUDController.__init__(self, model_object=self.model_object)
        self.local_menu = []

exposed = SpentLessonController()
